package com.example.zhangjingyu

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.zhangjingyu.R
import java.io.File

class FirstFragment : Fragment(), WordAdapter.OnDeleteClickListener {

    private lateinit var adapter: WordAdapter
    private lateinit var wordList: MutableList<Word>

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.first_frag, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())

        wordList = readWordsFromFile().toMutableList()
        adapter = WordAdapter(wordList, this)
        recyclerView.adapter = adapter
    }

    private fun readWordsFromFile(): List<Word> {
        val file = File(requireContext().filesDir, "words.txt")
        if (!file.exists()) {
            return emptyList()
        }
        return file.readLines().map { Word(it) }
    }

    override fun onDeleteClick(word: Word) {
        AlertDialog.Builder(requireContext())
            .setMessage("确定要删除这个单词吗？")
            .setPositiveButton("删除") { _, _ ->
                wordList.remove(word)
                adapter.notifyDataSetChanged()
                saveWordsToFile()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun saveWordsToFile() {
        val file = File(requireContext().filesDir, "words.txt")
        file.writeText(wordList.joinToString("\n") { it.text })
    }
}